<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      fullscreen
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改订单信息' : '添加订单信息'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.orderNo!=''&& form.orderNo!=null" style="width: 30%;color:var(--color-primary)" >采购订单号:{{ form.orderNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <!-- <el-col :md="6" :sm="24" >
            <el-form-item label="订单号:" >
              <el-input v-model="form.orderNo" placeholder="系统自动生成" disabled  >
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :md="6" :sm="24" >
            <el-form-item label="制单日期:"  prop="createDate">
              <el-date-picker v-model="form.createDate" type="date" placeholder="请输入发货日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="制单人:" prop="createUser">
              <el-select  v-model="form.createUser" filterable placeholder="请选择制单人" style="width:100%" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
              <el-form-item label="合同号:" prop="contractNumber">
                <el-input v-model="form.contractNumber" placeholder="请输入合同号"   >
                </el-input>
              </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="供应商:" prop="supplierId">
              <el-select  v-model="form.supplierId" filterable clearable placeholder="请选择供应商" style="width:100%" >
                <el-option  v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="发货日期:"  prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" type="date" placeholder="请输入发货日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="提单号:" prop="billNumber">
              <el-input v-model="form.billNumber" placeholder="请输入提单号"   >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="收货仓库:" prop="wareHouseId">
              <el-select  v-model="form.wareHouseId" filterable clearable placeholder="请选择收货仓库" style="width:100%"  >
                <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="6" :sm="24" >
            <el-form-item label="上传附件:"  >
              <el-input v-model="form.billNumber"  />
            </el-form-item>
          </el-col> -->
          <el-col :md='6' :sm='24' class="fujain">
            <el-form-item label="合同附件:">
              <el-upload action="#" ref="pictureUpload" :auto-upload="false" :show-file-list="false" class="upload-demo" :class="{hide:hideUpload}" :on-change="handleChange" :limit="1"
                :file-list="fileList" :on-remove="handleRemove" >
                <div v-show="!this.hideUpload" >
                  <span  class="el-icon-upload" type="warning" round>上传附件</span>
                </div>
              </el-upload>
              <div v-show="this.hideUpload" style="display: flex;align-items: center; justify-items: center; margin-top: -40px; width: 270px;height: 40px;" @mouseover="over" @mouseout="out">
                  <el-link :href="this.fileUrl" style="width:90%;align-content: center; height: 30px;" target="_blank" type="warning" icon="el-icon-upload" :underline="false">{{this.filename}}</el-link>
                  <!-- <div class="el-icon-upload" style="width:90%;align-content: center; height: 30px;" type="warning" round >{{ this.fileList.length>0?this.fileList[0].url:'' }}</div> -->
                  <div :class="[isOver ?'el-icon-close':'el-icon-circle-check']" style="width:10%;align-content: center; height: 30px;" type="warning" round @click="clearFile"></div>
                </div>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="采购金额:"  >
              <el-input v-model="form.purAmount" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :md="6" :sm="24" >
            <el-form-item label="海运费:"  >
              <el-input v-model="form.hyAmount"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="港杂费:"  >
              <el-input v-model="form.gzAmount"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="拖车费:"  >
              <el-input v-model="form.tyAmount" disabled  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="其他费:"  >
              <el-input v-model="form.qtAmount"  disabled />
            </el-form-item>
          </el-col> -->
          
          <el-col :md="18" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="1"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >产品列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="OpenProductList"  >选择产品 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight">
          <el-table-column type="index" width="50" align="center" label="序号" fixed='left'  />
          <el-table-column label="产品编号" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center"  >
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" >
              <template slot-scope="{ row }">
                  <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="数量" align="center" >
            <template slot-scope="{ row ,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                <el-input  v-model="row.qty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                  row.qty = row.qty.replace(/\.{2,}/g,'.');
                  row.qty = row.qty.replace(/^\./g,'');
                  row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="采购单价(￥)" align="center" width="120" >
              <template slot-scope="{ row ,$index}">
                <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.purPrice'" :rules="itemRules.purPrice">
                  <el-input  v-model="row.purPrice"  placeholder="请输入采购单价"  @change="setAmount(row,$index)" @keyup.native="row.purPrice = row.purPrice.replace(/[^\d.]/g,'');
                  row.purPrice = row.purPrice.replace(/\.{2,}/g,'.');
                  row.purPrice = row.purPrice.replace(/^\./g,'');
                  row.purPrice = row.purPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.purPrice = row.purPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="金额" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.amount }}</span>
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-input  v-model="row.amount"  prefix-icon="el-icon-_rmb" disabled />
              </el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column label="集装箱号" align="center" width="130">
            <template slot-scope="{ row, $index }">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.containerNumber'" :rules="itemRules.containerNumber" >
                <el-input v-model="row.containerNumber" placeholder="请输入集装箱号" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="收货仓库" align="center" width="130">
            <template slot-scope="{ row ,$index }">
              <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.receiveWareHouseId'" :rules="itemRules.receiveWareHouseId">
                <el-select  filterable v-model="row.receiveWareHouseId" placeholder="请选择收货仓库" class="ele-fluid" >
                  <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="行备注" align="center" width="200" >
            <template slot-scope="{ row }">
                <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3" fixed='right'  >
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  v-permission="'PurOrder_ProductList_Delete'" icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" >费用明细</div>
        <el-table :data="form.costs" ref="costs"  :border="true" style="width: 100%" >
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column label="费用名称" width="150" align="center" >
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span >{{ row.costDesc }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="费用公司名称" width="300" align="center">
            <template slot-scope="{ row, $index}">
              <el-form-item v-if="row.costNumber == 'C-FYLX01'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" >
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" @clear="clear(row)">
                  <el-option  v-for="item in HDCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              <el-form-item v-else-if="row.costNumber == 'C-FYLX02'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" >
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" @clear="clear(row)">
                  <el-option  v-for="item in TYCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              <el-form-item v-else-if="row.costNumber == 'C-FYLX04'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" >
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" @clear="clear(row)">
                  <el-option  v-for="item in QTCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              <el-form-item v-else-if="row.costNumber == 'C-FYLX05'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" >
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" @clear="clear(row)">
                  <el-option  v-for="item in HDCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="币种"  align="center">
            <template slot-scope="{ row , $index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'costs.'+ $index+'.currencyId'" :rules="row.supplierId?costsRules.currencyId:costsRules.currencyIdIsNull" >
                <el-select  filterable clearable v-model="row.currencyId" placeholder="请选择币种" class="ele-fluid" @change="(v)=>changeCurrency(v,$index)">
                  <el-option v-for="item in hbDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="金额"  align="center">
              <template slot-scope="{ row , $index }">
                <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.amount'" :rules="row.supplierId?costsRules.amount:costsRules.amountIsNull">
                  <el-input v-model="row.amount" placeholder="请输入金额" @change="setExchangeAmount(row,$index)"  @keyup.native="row.amount = row.amount.replace(/[^\d.]/g,'');
                  row.amount = row.amount.replace(/\.{2,}/g,'.');
                  row.amount = row.amount.replace(/^\./g,'');
                  row.amount = row.amount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.amount = row.amount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="汇率"  align="center">
            <template slot-scope="{ row , $index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'costs.'+ $index+'.rate'" :rules="row.currencyCode!='C-HB01'&&row.supplierId?costsRules.rate:null" >
                <!-- <el-input v-model="row.rate" placeholder="请输入汇率" @change="setExchangeAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                    row.rate = row.rate.replace(/\.{4,}/g,'.');
                    row.rate = row.rate.replace(/^\./g,'');
                    row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"/> -->

                <el-input v-if="row.currencyCode!='C-HB01'"   v-model="row.rate" placeholder="请输入汇率" :disabled="row.currencyCode=='C-HB01'" @change="setExchangeAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                    row.rate = row.rate.replace(/\.{4,}/g,'.');
                    row.rate = row.rate.replace(/^\./g,'');
                    row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                <span v-else>{{  row.rate }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="金额(￥)"  align="center">
              <template slot-scope="{ row  }">
                <span>{{ row.amountCn }}</span>
                <!-- <el-form-item label-width="10" style="margin-bottom:0;"  >
                  <el-input v-model="row.amountCn" disabled/>
                </el-form-item> -->
              </template>
          </el-table-column>
          <el-table-column label="行备注" align="center" width="200">
            <template slot-scope="{ row }">
                <el-input v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <div slot="footer">
      <el-button type="primary" v-show="this.btnIndex!=3 &&  form.status!=5"  :loading="loading" @click="save" v-permission="'PurOrder_Save'"  >
        挂单
      </el-button>
      <el-button type="warning" v-show="this.btnIndex!=3 &&  form.status!=5" :loading="loading" @click="settle" v-permission="'PurOrder_Audit'"  >
        过账
      </el-button>
      <el-button type="danger" v-show="form.status==5" :loading="loading" @click="unSettle"   >
        反过账
      </el-button>
      <el-button type="info" @click="print" v-show="form.orderNo!=''&& form.orderNo!=null" v-permission="'PurOrder_Print'" >打印</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
     <!-- 编辑弹窗 -->
     <productList :visible.sync="showProductList"  @callback="reloadItemList"/>
    </ele-modal>
  </template>
  <script>
   import { printHtml } from 'ele-admin';
   import productList from './product-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { QueryModelByScurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { QueryAttchmentByBusinessId ,GetGuid,DeleteAttachment} from '@/api/attchment';
   import { AddPurorder, UpdatePurorder,QueryPurorderById,SettlePurorder,PrintPurorderById,AntiSettlePurorder } from '@/api/businesshandling/purordermanager';

    export default {
      name: 'PurOrderEditCom',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {productList},
      data() {
        return {
          // 表单数据
          form: {createUser:'',createDate:''},
          fixedHeight:true,
          // 表单验证规则
          rules: {
            wareHouseId: [{required: true,message: '请选择收货仓',trigger: 'blur'}],
            deliveryDate: [{required: true,message: '请输入发货日期',trigger: 'blur'}],
            supplierId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
            // contractNumber: [{required: true,message: '请输入合同号',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            purPrice: [{required: true,message: '请输入采购单价',trigger: 'blur'}],
            containerNumber: [{required: true,message: '请输入集装箱',trigger: 'blur'}],
            receiveWareHouseId: [{required: true,message: '请输入收货仓库',trigger: 'blur'}],
          },
          costsRules: {
            amountIsNull: [{required: false}],
            rateIsNull: [{required: false}],
            currencyIdIsNull: [{required: false}],
            supplierIdIsNull: [{required: false}],

            amount: [{required: true,message: '请输入金额',trigger: 'blur'}],
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            currencyId: [{required: true,message: '请输入币种',trigger: 'blur'}],
            supplierId: [{required: true,message: '请输入第三方公司',trigger: 'blur'}],
          },
          fileUrl:'',
          filename:'',
          isOver:false,
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          showProductList:false,
          defaultDate:new Date(),
          hbDatas:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
          GZCompanyDatas:[],
          TYCompanyDatas:[],
          QTCompanyDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 500px)' : void 0;

          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 400px)' : null;

          return fh;
        },
      },
      //初始化数据
      mounted(){
        this.limit = 1;
        this.initData();
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            res.map((m)=>{
              if(m.typeId ==0){
                this.supplierDatas.push(m);
              }

            });

            
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          //海运费
          QuerySupplierByType(2).then((res)=>{
            this.HDCompanyDatas = [];
            this.HDCompanyDatas = res;
          });

          //运输公司
          QuerySupplierByType(1).then((res)=>{
            this.TYCompanyDatas = [];
            this.TYCompanyDatas = res;
          });

          //其他费用
          QuerySupplierByType(4).then((res)=>{
            this.QTCompanyDatas = [];
            this.QTCompanyDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.hbDatas = [];
            this.hbDatas = res;
          });
          
        },

        over(){
          this.isOver = true;
        },

        out(){
          this.isOver = false;
        },

        //
        setRequest(row){
          if(row.supplierId){
            this.costsRules.amount = [{required: true,message: '请输入金额',trigger: 'blur'}];
            this.costsRules.rate = [{required: true,message: '请输入汇率',trigger: 'blur'}];
            this.costsRules.currencyId = [{required: true,message: '请输入币种',trigger: 'blur'}];
            this.costsRules.supplierId = [{required: true,message: '请输入第三方公司',trigger: 'blur'}];
          }else{
            this.costsRules.rate=null;
            this.costsRules.amount = null;
            this.costsRules.currencyId= null;
            this.costsRules.supplierId=null;
          }
        },

        chagewarehouse(val){
          if(this.form.items){
            this.form.items.map((m)=>{
              m.receiveWareHouseId = this.form.wareHouseId;
            })
          }
        },

        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            //上传图片
            this.fileList.map((f) => {
              if (f.file != undefined) {
                f.fileType = 2
                this.uploadImg(f);
              }
            });

            this.setSharePrice();

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdatePurorder : AddPurorder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 过账 */
        settle() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            //上传图片
            this.fileList.map((f) => {
              if (f.file != undefined) {
                f.fileType = 2
                this.uploadImg(f);
              }
            });

            if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

            this.setSharePrice();

            this.loading = true;
            SettlePurorder(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 反过账 */
        unSettle() {

          this.loading = true;
          AntiSettlePurorder(this.form.id)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          QueryPurorderById(id)
            .then((res) => {
              this.form = res; 
              this.setAttchement(id);
              if(id==this.Constant.DefaultCostsId){
                let currentUser = getUser();
                this.$set(this.form,'createDate',this.defaultDate);
                this.$set(this.form,'createUser',currentUser.accountId)
              }

              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
              
          });
        },

         /* 从后面获取主键 */
        async getId(){
          if(!this.form.id){
          let id = await GetGuid();
          this.form.id = id;
          }
        },

       //赋值到附件
        setAttchement(id){
          QueryAttchmentByBusinessId(id).then((d)=>{
            this.fileList = [];
            d.map((item)=>{
              this.filename = item.fileName;
              this.fileUrl  = item.fileAllPath;
              this.fileList.push({
                id: item.id,
                name: item.fileName,
                url: item.fileAllPath,
                businessId: item.businessId,
                orderIndex: item.orderIndex,
              });
            });
            //设置上传图片按钮是否可见
            this.hideUpload = this.fileList.length >= this.limit;
          });
        },

        OpenProductList(){
          this.showProductList =true;
        },

        reloadItemList(orderData){

          if(this.form.items==null || this.form.items ==undefined){
            this.form.items = [];
          }

          orderData.map((item)=>{
            let product = this.form.items.find((d)=>{
              return d.productId == item.id && d.receiveWareHouseId == item.wareHouseId
            })
            if(product){
              this.$message.info('当前选择的产品'+product.productName+'在列表中已经存在');
              return;
            }else{
              this.form.items.push({
                orderId:this.form.id,
                productId:item.id,
                productCode:item.code,
                productName:item.name,
                receiveWareHouseId:item.wareHouseId?item.wareHouseId:this.form.wareHouseId,
                receiveWareHouseDesc:'',
                purPrice:item.purPrice,
                unitId:item.unitId,
                spc:item.spc,
                unitDesc:item.unitDesc,
                containerNumber:'',
                qty:0,
                amount:0,
                remarks:item.remarks,
              })
            }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });
        },

        changeCurrency(val,index){
          let hb = this.hbDatas.find((p)=>p.id === val)
          if(hb){
           this.$refs.costs.data[index].currencyCode = hb.code;
           if(hb.code == 'C-HB01'){
              this.$refs.costs.data[index].rate = 1;
              this.$refs.costs.data[index].amountCn = this.$refs.costs.data[index].amount;
           }else{
            QueryModelByScurrencyId(val).then((res)=>{
              this.$refs.costs.data[index].rate = res?res.rate:0;
              
              let rate = parseFloat(res?res.rate:0);
              this.$refs.costs.data[index].amountCn = (this.$refs.costs.data[index].amount * rate ).toFixed(4);
            })
           }
          }
        },

        clear(row){
          row.rate = 0;
          row.amount = 0;
          row.amountCn = 0;
          row.currencyId = '';
          row.supplierTypeId = '';
        },

        //选择第三方公司
        changeThreeCompany(row,val,index){

          if(row.costNumber == 'C-FYLX01'){

            let hdCompany = this.HDCompanyDatas.find((p)=>p.id === val)
            if(hdCompany){
              this.$refs.costs.data[index].rate = hdCompany.rate;
              this.$refs.costs.data[index].currencyId = hdCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = hdCompany.typeId;
              this.changeCurrency(hdCompany.currencyId,index);
            }

          }else if(row.costNumber == 'C-FYLX02'){

            let tyCompany = this.TYCompanyDatas.find((p)=>p.id === val)
            if(tyCompany){
              this.$refs.costs.data[index].rate = tyCompany.rate;
              this.$refs.costs.data[index].currencyId = tyCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = tyCompany.typeId;
              this.changeCurrency(tyCompany.currencyId,index);
            }

          }else if(row.costNumber == 'C-FYLX04'){

            let qtCompany = this.QTCompanyDatas.find((p)=>p.id === val)
            if(qtCompany){
              this.$refs.costs.data[index].rate = qtCompany.rate;
              this.$refs.costs.data[index].currencyId = qtCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = qtCompany.typeId;
              this.changeCurrency(qtCompany.currencyId,index);
            }
          }else if(row.costNumber == 'C-FYLX05'){
            let hdCompany = this.HDCompanyDatas.find((p)=>p.id === val)
            if(hdCompany){
              this.$refs.costs.data[index].rate = hdCompany.rate;
              this.$refs.costs.data[index].currencyId = hdCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = hdCompany.typeId;
              this.changeCurrency(hdCompany.currencyId,index);
            }
          }

          
          
        },

        //设置金额
        setAmount(row,index){
          if(row.purPrice && row.qty){
              let qty = parseFloat(row.qty);
              let purPrice = parseFloat(row.purPrice);
              this.$refs.items.data[index].amount = (purPrice * qty).toFixed(2);
          }

          this.setPurAmountTotal();
        },

        //费用分摊
        //A产品采购金额10元
        //B产品采购金额20元
        //A/B产品总共产生了6元的运费
        //那么A产品分摊6÷（10+20）×10=2元
        //B产品分摊6÷（10+20）×20=4元
        setSharePrice(){

          var amount = 0
          var costAmountcn = 0;
          var puramount = parseFloat(this.form.purAmount);

          if(this.form.costs!=null && this.form.costs!=undefined){
            costAmountcn =  this.form.costs.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amountCn?cur.amountCn:0)  },0);
          }

          if(this.form.items!=null && this.form.items!=undefined){
            amount = costAmountcn/puramount;
            this.form.items.map((item,index)=>{
              var amounttotal = amount * item.amount;
              this.form.items[index].sharePrice = parseFloat(item.qty)<=0?0:(amounttotal/parseFloat(item.qty)).toFixed(4);
            })
          }
        },

   

        /* 删除 */
        remove(_row, index) {
          this.form.items.splice(index, 1);
          this.setPurAmountTotal();
        },

        //设置采购金额
        setPurAmountTotal(){
          this.form.purAmount = 0;
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            this.form.purAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amount)  },0);
            this.form.purAmount =this.form.purAmount.toFixed(2);
          }
        },

        setExchangeAmount(row,index){
          if(row.amount && row.rate){
              let rate = parseFloat(row.rate);
              let amount = parseFloat(row.amount);

              if(row.costNumber =='C-FYLX02')this.form.tyAmount = amount;  //拖运费
              if(row.costNumber =='C-FYLX01')this.form.gzAmount = amount;  //港杂费
              if(row.costNumber =='C-FYLX04')this.form.qtAmount = amount;  //港杂费
              if(row.costNumber =='C-FYLX05')this.form.hyAmount = amount;  //港杂费

              if(row.currencyCode == 'C-HB01'){
                this.$refs.costs.data[index].rate =1;
                this.$refs.costs.data[index].amountCn = amount;
              }else{
                this.$refs.costs.data[index].amountCn = (amount * rate ).toFixed(4);
              }
          }
        },

        clearFile(){
         

          if(this.isOver){
            this.$confirm('是否确认删除该图片?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 执行删除操作
              if(this.fileList!=null&&this.fileList.length>0){
                DeleteAttachment(this.fileList[0].id).then((e)=>{
                  this.fileList=[];
                  this.hideUpload  =false;
                  this.$message('删除成功!');
                  this.close();
                });
              }
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
              this.fileList=[];
              this.hideUpload  =false;
            })
          }
        },

         //上传图片
        handleChange(file, fileList) {
          
          let obj = {
            orderIndex: 1, //默认值
            attType: 2, //文件类型(1:图片,2:文件)
            file: file.raw, // 文件流
            fileName: file.name, // 文件名称
            url:file.url,// 文件路径
          }

          this.fileUrl = file.name;
          this.filename = file.name;
          // //读取文件流到本地
          // let reader = new FileReader();
          // reader.readAsText(file.raw);
          // reader.onload = e=> {
          //   this.filecontent = e.target.result.replace(/\n|\r\n/g,'<br/>')
          // };
          //索引
          if(fileList!=null && fileList.length>0){
            obj.orderIndex = fileList.length;
          }
          //业务id 新增页面时，从后台获取Guid
          if(this.form){
            obj.businessId = this.form.id;  
          }
          //文件列表
          this.fileList.push(obj);
          
          //设置上传图片按钮是否可见
          if(this.fileList!=null && this.fileList!=undefined){
            this.hideUpload = this.fileList.length >= this.limit;
          }else{
            this.hideUpload =false;
          }
        },

        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
          this.fileList= [];
        },

        handleClose() {
          this.$emit('update:visible', false);
          this.fileList= [];
        },


        // 打印
        print(){
          PrintPurorderById(this.form.id).then((data)=>{
            const pWindow = printHtml({
                html: data, // 要打印的内容
                // style: '<style>span { color: red; }</style>',  // 页面样式
                // title: '', // 页面标题，浏览器打印设置显示页眉会显示页面标题
                horizontal: true, // 是否横向打印
                blank: true, // 是否打开新页面打印
                close: true, // 如果是打开新页面，打印完是否关闭
                print: true, // 如果是打开新窗口是否自动打印
                iePreview: true, // 是否兼容 ie 打印预览
                loading: true, // 是否显示 loading
                before: () => { // 打印开始的回调
                },
                done: () => { // 打印完成的回调
                },
                margin: 0, // 页间距
                header: '', // 页眉 html
                footer: '' // 页脚 html
            });
          });
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={};
              this.getId();
              this.fileList=[];
              this.isUpdate = false;
              this.hideUpload =false;
              this.setData(this.Constant.DefaultCostsId);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
              let currentUser = getUser();
              this.form.createUser = currentUser.accountId;
              this.form.createDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>